var WALL_THICKNESS = 4;
var FRAMES_PER_SECOND = 20;
var NUMBER_OF_PARTICLES = 500;
var RESAMPLE_DELAY = 20; //A smaller number increase resample frequency
var SENSOR_NOISE = 40;
var MOVE_NOISE = 0.4;
var TURN_NOISE = 0.2;

var WORLD_WIDTH;
var WORLD_HEIGHT;
var WALLS;
var H_WALLS;
var V_WALLS;
var ROBOT;

World = function (gs, level) {
	WORLD_WIDTH = gs.width;
	WORLD_HEIGHT = gs.height;	
	
	WALLS = [];	
	H_WALLS = [];
	V_WALLS = [];
	createWalls(gs, level.hWalls, false);
	createWalls(gs, level.vWalls, true);
	H_WALLS.sort(function(w1, w2) { return w1.pos - w2.pos;});
	V_WALLS.sort(function(w1, w2) { return w1.pos - w2.pos;});
	
	createRobot(gs, level.initialX, level.initialY, level.initialH);
}

function createWalls(gs, walls, isVertical) {
	for (var i = 0; i < walls.length; i++) 
		createWall(gs, walls[i], isVertical);
}

function createWall(gs, wallInfo, isVertical) {
	var createWall = isVertical ? createVerticalWall : createHorizontalWall;
	var wallList = isVertical ? V_WALLS : H_WALLS;
	var wall = createWall(wallInfo);
	gs.addEntity(wall);	
	WALLS.push(wall);
	wallList.push(wall);	
}

function createHorizontalWall(wallInfo) {
	var pos = translateVerticalCoordinate(wallInfo.pos);
	var start = translateHorizontalCoordinate(wallInfo.start);
	var end = translateHorizontalCoordinate(wallInfo.end);
	return new Wall(pos, start, end, false);
}

function createVerticalWall(wallInfo) {
	var pos = translateHorizontalCoordinate(wallInfo.pos);
	var start = translateVerticalCoordinate(wallInfo.start);
	var end = translateVerticalCoordinate(wallInfo.end);
	return new Wall(pos, start, end, true);
}

function createRobot(gs, x, y, h) {	
	var robotX = translateHorizontalCoordinate(x);
	var robotY = translateVerticalCoordinate(y);
	ROBOT = new Robot(robotX, robotY, h);
	gs.addEntity(ROBOT);
}

function startGame() {
    var gs = new JSGameSoup("surface", FRAMES_PER_SECOND);
	var world = new World(gs, getFirstLevel());
	var filter = new ParticleFilter(gs);
	
    gs.launch();
}

function translateHorizontalCoordinate(x) {
	return ((x/100) * (WORLD_WIDTH - 2 * WALL_THICKNESS)) + WALL_THICKNESS;
}

function translateVerticalCoordinate(y) {
	return ((y/100) * (WORLD_HEIGHT - 2 * WALL_THICKNESS)) + WALL_THICKNESS;
}